package com.dubbo.provider;

import com.alibaba.dubbo.common.URL;
import com.alibaba.dubbo.config.ApplicationConfig;
import com.alibaba.dubbo.config.ProtocolConfig;
import com.alibaba.dubbo.config.RegistryConfig;
import com.alibaba.dubbo.config.ServiceConfig;
import com.dubbo.provider.service.OrderInfoService;
import com.dubbo.provider.service.OrderInfoServiceImpl;
import com.dubbo.provider.service.UserService;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.io.IOException;

import java.util.List;

public class StartApplication {
    public void openService(int port) {
        // 服务配置
        ServiceConfig serviceConfig = new ServiceConfig();
        ServiceConfig serviceConfig2 = new ServiceConfig();
        // 设置服务接口
        serviceConfig.setInterface(OrderInfoService.class);
        serviceConfig2.setInterface(UserService.class);
        // 设置开放的协议
        serviceConfig.setProtocol(new ProtocolConfig("dubbo", port));
        // 设置一个空的注册中心
        serviceConfig.setRegistry(new RegistryConfig("zookeeper://127.0.0.1:2181"));
        // 设置服务当前所在应用
        serviceConfig.setApplication(new ApplicationConfig("simple-app"));
        // 设置随机
        serviceConfig.setLoadbalance("random");
        // 设置服务实现对象
        OrderInfoServiceImpl ref = new OrderInfoServiceImpl();
        serviceConfig.setRef(ref);
        // 暴露服务
        serviceConfig.export();
        List<URL> list = serviceConfig.getExportedUrls();
        ref.setPort(list.get(0).getPort());
        System.out.println("服务已开启 :" + list.get(0).getPort());
    }

    // 20880 20881
    public static void main(String[] args) throws IOException {
       //new StartApplication().openService(-1);
        ClassPathXmlApplicationContext context = new
                ClassPathXmlApplicationContext("dubbo/dubbo-provider.xml");
        context.start();
        System.in.read();
    }
}
